package org.guderin.bookmarkus.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.guderin.bookmarkus.model.Bookmark;

public class BookmarkDao {

	@SuppressWarnings("unchecked")
	public List<Bookmark> list() {

		EntityManager em = EMFService.get().createEntityManager();
		Query q = em.createQuery("select m from Bookmark m");
		List<Bookmark> bookmarks = q.getResultList();
		return bookmarks;
	}

	public void add(String author, String url, String description, String name) {
		synchronized (this) {
			EntityManager em = EMFService.get().createEntityManager();
			Bookmark bookmark = new Bookmark(author, url, description, name);
			em.persist(bookmark);
			em.close();
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Bookmark> getBookmarksByAuthor(String author) {
		EntityManager em = EMFService.get().createEntityManager();
		Query q = em
				.createQuery("select t from Bookmark t where t.author = :author");
		q.setParameter("author", author);
		List<Bookmark> Bookmarks = q.getResultList();
		return Bookmarks;
	}

	public void remove(long id) {
		EntityManager em = EMFService.get().createEntityManager();
		try {
			Bookmark bookmark = em.find(Bookmark.class, id);
			em.remove(bookmark);
		} finally {
			em.close();
		}
	}
	
}
